/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package se.sll.service.catalogue.camel.component.snod;

import lombok.extern.slf4j.Slf4j;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.impl.DefaultConsumer;
import se.sll.service.catalogue.common.property.CatalogProperties;
import se.sll.snod.SnodClient;

/**
 *
 * @author khaleddaham
 */
@Slf4j
public class SnodConsumer extends DefaultConsumer {

    private final SnodEndpoint endpoint;
    private SnodClient client;
    
    public SnodConsumer(SnodEndpoint endpoint, Processor processor) {
        super(endpoint, processor);
        this.endpoint = endpoint;
    }

    @Override
    protected void doStart() throws Exception {
        client = new SnodClient(
                CatalogProperties.getProperty(CatalogProperties.NAME.SNOD_VTGET_HOST),
                CatalogProperties.getProperty(CatalogProperties.NAME.SNOD_VTGET_PORT),
                CatalogProperties.getProperty(CatalogProperties.NAME.SNOD_VTGET_SERVICE),
                CatalogProperties.getProperty(CatalogProperties.NAME.SNOD_VTGET_USERNAME),
                CatalogProperties.getProperty(CatalogProperties.NAME.SNOD_VTGET_PASSWORD));
        client.queryService("vantetider.xml");
        sendExchange(client.getResult());
    }

    @Override
    protected void doStop() throws Exception {
        //client.close();
    }

    /**
     * Whether the timer task is allow to run or not
     */
    protected boolean isTaskRunAllowed() {
        // only allow running the timer task if we can run and are not suspended,
        // and CamelContext must have been fully started
        return endpoint.getCamelContext().getStatus().isStarted() && isRunAllowed() && !isSuspended();
    }

    protected void sendExchange(String data) {
        log.info("****");
        log.info(data);
        log.info("****");
        Exchange exchange = endpoint.createExchange();
        exchange.setProperty("vtget", data);

        log.trace("Snod {} is firing #{} count", endpoint.getVersion());
        try {
            getProcessor().process(exchange);
        } catch (Exception e) {
            exchange.setException(e);
        }

        // handle any thrown exception
        if (exchange.getException() != null) {
            getExceptionHandler().handleException("Error processing exchange", exchange, exchange.getException());
        }
    }
}